package com.atguigu.flink08;

import com.atguigu.beans.WaterSensor;
import com.atguigu.func.WaterSensorMapFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @author Felix
 * @date 2024/2/27
 * 该案例演示了状态的失效时间设置
 * 检测每种传感器的水位值，如果连续的两个水位差值超过10，就输出报警
 */
public class Flink08_State_TTL {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> wsDS = env
                .socketTextStream("hadoop102", 8888)
                .map(new WaterSensorMapFunction());

        wsDS
                .keyBy(WaterSensor::getId)
                .process(
                        new KeyedProcessFunction<String, WaterSensor, String>() {
                            //键控状态和普通变量不一样的地方
                            // 1.键控状态是按key隔离，普通变量是所有key共享
                            // 2.状态可以被备份  普通变量只在内存中保存

                            //定义键控状态下的值状态  用于存放上次水位值
                            //注意：不能在声明状态的时候直接进行初始化，因为这个时候获取不到运行是上下文
                            //ValueState<Integer> lastVcState = getRuntimeContext().getState(valueStateDescriptor);
                            ValueState<Integer> lastVcState;

                            @Override
                            public void open(Configuration parameters) throws Exception {
                                //创建状态描述器  对状态进行描述
                                ValueStateDescriptor<Integer> valueStateDescriptor
                                        = new ValueStateDescriptor<Integer>("lastVcState", Integer.class);

                                //设置状态的失效时间
                                //注意：这里的时间指的是处理时间
                                valueStateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(Time.seconds(10))
                                        //.setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                        //.setUpdateType(StateTtlConfig.UpdateType.OnReadAndWrite)
                                        .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
                                        .build());

                                //在open方法中，对状态进行初始化
                                lastVcState = getRuntimeContext().getState(valueStateDescriptor);
                            }

                            @Override
                            public void processElement(WaterSensor ws, KeyedProcessFunction<String, WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                                //获取当前水位值
                                Integer curVc = ws.vc;
                                //从状态中获取上次水位值
                                Integer lastVc = lastVcState.value() == null ? 0 : lastVcState.value();

                                String id = ctx.getCurrentKey();
                                if (Math.abs(curVc - lastVc) > 10) {
                                    out.collect("传感器id" + id + "的当前水位值" + curVc + "和上一个水位值" + lastVc + "差大于10");
                                }
                                //将当前水位值更新到状态中
                                if (curVc > 10) {
                                    lastVcState.update(curVc);
                                }
                            }
                        }
                ).printToErr();

        env.execute();
    }
}
